package bigoo.peer;

import static java.util.logging.Logger.GLOBAL_LOGGER_NAME;

import java.io.IOException;
import java.net.InetAddress;
import java.util.logging.Logger;

import bigoo.common.communication.MessageBuilderFactory;
import bigoo.common.communication.tcp.TCPCommunication;
import bigoo.ds.message.GetPeersAnswerMessage;
import bigoo.ds.message.ImAliveAnswerMessage;
import bigoo.peer.message.AcceptRideAnswerMessage;
import bigoo.peer.message.AcceptRideMessage;
import bigoo.peer.message.ConfirmRideMessage;
import bigoo.peer.message.PublishRideMessage;
import bigoo.peer.message.RejectedRideMessage;
import bigoo.peer.message.RideRequestMessage;
import bigoo.util.Config;

public class BigooRunner {

    public static void main(String[] args) throws SecurityException, IOException {
	if (args.length < 1) {
	    System.err.println("usage: BigooRunner <peerID>");
	    System.exit(-1);
	}

	Config.loadProperties(Config.BIGOO_PROPERTIES);
	Config.configureLog();
	Logger logger = Logger.getLogger(GLOBAL_LOGGER_NAME);

	// parsing args and starting
	String address = InetAddress.getLocalHost().getHostAddress();

	MessageBuilderFactory factory = MessageBuilderFactory.getInstance();
	factory.registerBuilder(ImAliveAnswerMessage.MSG_IDENTIFIER, new ImAliveAnswerMessage.Builder());
	factory.registerBuilder(GetPeersAnswerMessage.MSG_IDENTIFIER, new GetPeersAnswerMessage.Builder());
	factory.registerBuilder(PublishRideMessage.MSG_IDENTIFIER, new PublishRideMessage.Builder());
	factory.registerBuilder(RideRequestMessage.MSG_IDENTIFIER, new RideRequestMessage.Builder());
	factory.registerBuilder(RejectedRideMessage.MSG_IDENTIFIER, new RejectedRideMessage.Builder());
	factory.registerBuilder(AcceptRideMessage.MSG_IDENTIFIER, new AcceptRideMessage.Builder());
	factory.registerBuilder(AcceptRideAnswerMessage.MSG_IDENTIFIER, new AcceptRideAnswerMessage.Builder());
	factory.registerBuilder(ConfirmRideMessage.MSG_IDENTIFIER, new ConfirmRideMessage.Builder());

	int port = Integer.parseInt(Config.getProperties().getProperty(Config.PEER_PORT));
	logger.config("port => " + port);

	BigooPeer bigooPeer = new BigooPeer(new TCPCommunication(port), args[0], address);
	bigooPeer.start();
	logger.info("Bigoo is UP and RUNNING!");
	
	BigooUI ui = new BigooUI(bigooPeer);
	ui.run();
    }

}
